package gpl.pierrick.brihaye.util;

import java.util.Map;

public class StringOperations {
	/**
	 * This function translates the given word according
	 * to the given translation map. The characters of the word
	 * will be traversed one by one and replaced according
	 * to the translation map.
	 * @param word the word to be translated.
	 * @param translationMap maps each character in input to a Character
	 * of a String to be replaced with it. The special character '\0' is used
	 * to map unwanted characters
	 * @return the words after translation. An empty string if all characters
	 * of input word were dropped (mapped to '\0')
	 */
	public static String translate(String word, Map<Character,Object> translationMap) {
		char[] translatedGloss = new char[word.length() * 2];
		int i=0;
		char[] arGloss = word.toCharArray();
		
		for (int x = 0;x < arGloss.length;x++) {
			Object result = translationMap.get(new Character(arGloss[x]));
			if (result == null)
				translatedGloss[i++] = arGloss[x];
			else if (result instanceof Character) {
				Character temp1 = (Character)result;
				//null character is a special case to ignore this letter in output
				if (temp1 != '\0')
					translatedGloss[i++] = temp1.charValue();
			} else /*instance of String*/{
				String temp1 = (String)result;
				char temp2[] = temp1.toCharArray();
				for (int j = 0; j < temp2.length;j++)
					translatedGloss[i++]=temp2[j];
			}
		}
		return new String(translatedGloss,0,i);
	}


}
